#include "stdafx.h"
#include "EntityManager.h"
#include "Entity.h"
#include "SceneManager.h"
#include "Heightmap.h"

EntityManager::EntityManager(SceneManager* scene_manager)
	: m_scene_manager(scene_manager){}


EntityManager::~EntityManager(void){
	if (m_entities.empty())
		return;

	auto it = m_entities.begin();

	while (it != m_entities.end()){
		m_scene_manager->Destroy((*it)->GetSceneObject());
		delete (*it)->m_render_object;
		(*it)->m_render_object = nullptr;
		delete *it;
		*it = nullptr;
		it++;
	}
	m_entities.clear();
}

void EntityManager::AddEntity(Entity* entity){
	m_entities.push_back(entity);
}

void EntityManager::RemoveEntity(Entity* entity){
	m_queue_list.push_back(entity);
	/*for (auto it = m_entities.begin(); it != m_entities.end(); it++)
	{
		if (*it == entity)
		{
			m_scene_manager->Destroy(entity->GetSceneObject());
			delete entity;
			m_entities.erase(it);
			break;
		}
	}*/
}

void EntityManager::RemoveEntity(unsigned int id){
	/*for (auto it = m_entities.begin(); it != m_entities.end(); it++){
		if ((*it)->GetId() == id){
			m_scene_manager->Destroy((*it)->GetSceneObject());
			delete *it;
			m_entities.erase(it);
			break;
		}
	}*/
}

void EntityManager::Update(float deltatime) {
	if (!m_queue_list.empty()) {
		for (auto it = m_queue_list.begin(); it != m_queue_list.end(); it++){
			m_scene_manager->Destroy((*it)->GetSceneObject());
			Remove(*it);
		}
		m_queue_list.clear();
	}

	for (unsigned int i = 0; i < m_entities.size(); i++){
		m_entities[i]->Update(deltatime);
	}
}

inline void EntityManager::Remove(Entity* entity){
	for (auto it = m_entities.begin(); it != m_entities.end(); it++){
		if (*it == entity){
			m_scene_manager->Destroy((*it)->GetSceneObject());
			delete (*it)->m_render_object;
			m_entities.erase(it);
			delete entity;
			return;
		}
	}
}